package com.luych.toolbox.gateway.center.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.luych.toolbox.common.event.base.service.WebSocketChatRemoteApplicationEvent;
import com.luych.toolbox.gateway.center.websocket.WebSocketEndPoint;
import com.luych.toolbox.gateway.center.websocket.WebSocketMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class WebSocketChatListener implements ApplicationListener<WebSocketChatRemoteApplicationEvent> {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketChatListener.class);

    private final ObjectMapper objectMapper;
    private final WebSocketEndPoint webSocketEndPoint;

    @Autowired
    public WebSocketChatListener(ObjectMapper objectMapper, WebSocketEndPoint webSocketEndPoint) {
        this.objectMapper = objectMapper;
        this.webSocketEndPoint = webSocketEndPoint;
    }

    @Override
    public void onApplicationEvent(WebSocketChatRemoteApplicationEvent event) {
        WebSocketMessage message = new WebSocketMessage(event.getChat());
        try {
            webSocketEndPoint.onSend(event.getUserId(), objectMapper.writeValueAsString(message));
        } catch (IOException e) {
            logger.error("websocket send chat, userId: {}, error: {}", event.getUserId(), e.getMessage(), e);
        }
    }
}
